package com.feihong.yw189.paidan.fragment.paidan;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.feihong.yw189.R;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.fragment.base.BaseFragment;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.paidan.activity.DispatchActivity;
import com.feihong.yw189.paidan.adapter.HoistryListAdapter;
import com.feihong.yw189.paidan.adapter.PaiDanOrderAdapter;
import com.feihong.yw189.paidan.bean.ListOrderInfo;
import com.feihong.yw189.paidan.tools.RefReshToken;
import com.feihong.yw189.popupwindow.SearchTypePopupWindow;
import com.google.gson.Gson;
import com.holenzhou.pullrecyclerview.PullRecyclerView;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 订单页基类(公共方法)
 * 张鹏
 * 2018.3.1
 */
@RuntimePermissions
public class BaseOrderList extends BaseFragment {
    private EditText ed_search;
    private DispatchActivity mActivity;
    private RelativeLayout mNoDataLayout;
    private HoistryListAdapter dispatchListAdapter;
    private PullRecyclerView mPullRecyclerView;
    private LinearLayout mSearchLayout;
    public int flag1 = 0;
    private PopupWindow popupWindow;
    private SearchTypePopupWindow showPopupWindow;
    private String search = "";
    public View fragmentView = null;
    private int screenHeight;
    private TextView serchtype;
    private LinearLayout mConnectErrorLayout;
    private TextView mRequeryDataTv;
    private int dataSize = 0;

    private PaiDanOrderAdapter mPaiDanOrderAdapter;

    public void setPaiDanOrderAdapter(PaiDanOrderAdapter mPaiDanOrderAdapter) {
        this.mPaiDanOrderAdapter = mPaiDanOrderAdapter;
    }

    public static BaseOrderList newInstance(String tabName) {
        BaseOrderList rechargeFragment = new BaseOrderList();

        return rechargeFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.item_pd_hositry, container, false);
        return fragmentView;

    }

    @Override
    protected void setTheme() {
        isDrakFont = false;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (DispatchActivity) getActivity();
        WindowManager wm = mActivity.getWindowManager();

        screenHeight = wm.getDefaultDisplay().getHeight();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        ed_search.setText("");
        bindData();
    }

    private void showPop() {
//        if (!popupWindow.isShowing()) {
        if (Build.VERSION.SDK_INT < 24) {
            popupWindow.showAsDropDown(mSearchLayout);
        } else {
            int[] location = new int[2];
            // 获取控件在屏幕的位置
            mSearchLayout.getLocationOnScreen(location);
            if (Build.VERSION.SDK_INT >= 25) {
                int tempheight = popupWindow.getHeight();
                if (tempheight == WindowManager.LayoutParams.MATCH_PARENT || screenHeight <= tempheight) {
                    popupWindow.setHeight(screenHeight - location[1] - mSearchLayout.getHeight());
                }
            }
            popupWindow.showAtLocation(mSearchLayout, Gravity.NO_GRAVITY, location[0], location[1] + mSearchLayout.getHeight());
        }
    }

    private int orderType = 0;

    public void setOrderType(int orderType) {
        this.orderType = orderType;
    }

    /**
     * 初始化布局
     */
    @Override
    public void initView() {

        mConnectErrorLayout = fragmentView.findViewById(R.id.connect_net_error_layout);
        mRequeryDataTv = fragmentView.findViewById(R.id.requery_data_tv);
        mNoDataLayout = fragmentView.findViewById(R.id.null_data_layout);
        mSearchLayout = fragmentView.findViewById(R.id.ll_type);
        ed_search = fragmentView.findViewById(R.id.ed_search);
        mPullRecyclerView = fragmentView.findViewById(R.id.pull_recycler_view);
        serchtype = fragmentView.findViewById(R.id.serchtype);
        // 做出搜索

        dispatchListAdapter = new HoistryListAdapter(_mActivity);
        // 设置权限监听
        dispatchListAdapter.setItemSelectListener(num -> {
            mTelNum = num;
            BaseOrderListPermissionsDispatcher.needpermissionWithCheck(BaseOrderList.this);
        });
        // 设置数据适配器
        mPullRecyclerView.setAdapter(dispatchListAdapter);
        // 设置下拉刷新的旋转圆圈的颜色
        mPullRecyclerView.setColorSchemeResources(R.color.orange);
        // 开启下拉刷新，默认即为true，可不用设置
        mPullRecyclerView.enablePullRefresh(true);
        // 开启数据全部加载完成时的底部提示，默认为false
        mPullRecyclerView.enableLoadDoneTip(true, R.string.load_done_tip);
        mPullRecyclerView.enableLoadMore(false);
        showPopupWindow = new SearchTypePopupWindow(mActivity, str -> {
            page = 1;
            flag1 = 0;
            if (popupWindow != null) {
                popupWindow.dismiss();
            }
            dataSize = 0;
            dispatchListAdapter.clear();
            // 做出搜索
            getData(search, str);
        });
        popupWindow = showPopupWindow.showPopupWindow();

        serchtype.setOnClickListener(v -> {
            closeInputMethod(serchtype);
            if (flag1 == 1) {
                flag1 = 0;
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
            } else {
                flag1++;
                if (popupWindow != null) {
                    showPop();
                }
            }
        });
        mPullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {
                page = 1;
                ed_search.setText("");
                dispatchListAdapter.clear();
                dataSize = 0;
                mPullRecyclerView.enableLoadMore(true);
                getData("", "");
            }

            @Override
            public void onLoadMore() {
                ed_search.setText("");
                getData("", "");
            }
        });
        ed_search.setOnClickListener(v -> {
            flag1 = 0;
            if (popupWindow != null) {
                popupWindow.dismiss();
            }
        });
        // 监听软键盘回车事件
        ed_search.setOnEditorActionListener((v, actionId, event) -> {

            if (actionId == EditorInfo.IME_ACTION_SEND
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NONE
                    || actionId == EditorInfo.IME_ACTION_GO
                    || actionId == EditorInfo.IME_ACTION_SEARCH
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || (event != null && KeyEvent.KEYCODE_ENTER
                    == event.getKeyCode() && KeyEvent.ACTION_DOWN
                    == event.getAction())) {
                closeInputMethod(ed_search);
                page = 1;
                //处理事件
                search = ed_search.getText().toString().trim();
                if (!TextUtils.isEmpty(search)) {
                    dataSize = 0;
                    dispatchListAdapter.clear();
                    getData(search, "");
                }
            }
            return true;
        });
        // 已完成订单取消成功之后需要刷新
        dispatchListAdapter.setRefOrderListListener(() -> mPullRecyclerView.autoRefresh());

        mRequeryDataTv.setOnClickListener(v -> {
            normalData();
            mPullRecyclerView.autoRefresh();
        });
    }

    @Override
    public void bindData() {
        getData("", "");
    }

    private String mTelNum = "";

    private int page = 1;
    private HashMap<String, String> numMap = new HashMap<>();
    private ArrayList<String> dataType = new ArrayList<>();

    private void getData(final String order_no, final String data) {
        App.getApp().getHttpTools().getHistoryList(order_no, data, orderType,
                "list", page, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        if (_mActivity == null || _mActivity.isDestroyed() || _mActivity.isFinishing() || fragmentIsOnDestory()) {
                            return;
                        }
                        dataType = new ArrayList<>();
                        if (mPullRecyclerView != null) {
                            mPullRecyclerView.postDelayed(() -> {
                                mPullRecyclerView.stopRefresh();
                                mPullRecyclerView.stopLoadMore();
                            }, 300);
                        }
                        try {
                            Gson gson = new Gson();
                            ListOrderInfo paiDanOrder = gson.fromJson(result, ListOrderInfo.class);
                            if (paiDanOrder == null) {
                                if (dataSize == 0) {
                                    mPullRecyclerView.enableLoadMore(false);
                                    noData();
                                }
                                return;
                            }

                            if (paiDanOrder.getStatus() == 1) {
                                dataType.addAll(paiDanOrder.getDate_type_list());
                                showPopupWindow.setData(dataType);
                                // 更新搜索时间类型适配器数据

                                numMap = new HashMap<>();
                                ListOrderInfo.StatusNum status_num = paiDanOrder.getStatus_num();

                                String allorder = status_num.getAll();
                                String finishorder = status_num.getOk();
                                String cancleordEr = "已取消";

                                allorder = "全部 (" + allorder + ")";
                                finishorder = "已完成(" + finishorder + ")";

                                numMap.put("0", allorder);
                                numMap.put("1", finishorder);
                                numMap.put("2", cancleordEr);

                                if (mPaiDanOrderAdapter != null) {
                                    mPaiDanOrderAdapter.setData(numMap);
                                }

                                if (paiDanOrder.getData() == null || paiDanOrder.getData().getData().size() == 0) {
                                    if (dataSize == 0) {
                                        mPullRecyclerView.enableLoadMore(false);
                                        noData();
                                    }
                                } else {
                                    List<ListOrderInfo.DataBean.OrderItemBean> data = paiDanOrder.getData().getData();
                                    if (data.size() < 20) {
                                        mPullRecyclerView.enableLoadMore(false);
                                    } else {
                                        page++;
                                    }
                                    dataSize += data.size();
                                    dispatchListAdapter.addAll(data);
                                    normalData();
                                }
                            } else if (paiDanOrder.getStatus() == 401) {

                                Boolean sucRef = RefReshToken.refshToken();
                                if (sucRef) {
                                    getData(order_no, data);
                                } else {
                                    RefReshToken.exitLogin();
                                }
                            } else {
                                if (dataSize != 0) {
                                    normalData();
                                } else {
                                    noData();
                                }
                                ToastUtils.showShortToast(mActivity, paiDanOrder.getInfo());
                            }
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        if (_mActivity == null || _mActivity.isDestroyed() || _mActivity.isFinishing() || fragmentIsOnDestory()) {
                            return;
                        }
                        if (mPullRecyclerView != null) {
                            mPullRecyclerView.postDelayed(() -> {
                                mPullRecyclerView.stopLoadMore();
                                mPullRecyclerView.stopRefresh();
                            }, 300);
                        }
                        if (dataSize == 0) {
                            connectNetError();
                        } else {
                            normalData();
                            showToast(getResources().getString(R.string.connect_sever_error_toast));
                        }
                    }

                    @Override
                    public void onCancelled(Callback.CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });

    }

    private void normalData() {

        if (mSearchLayout.getVisibility() != View.VISIBLE) {
            mNoDataLayout.setVisibility(View.GONE);
            mConnectErrorLayout.setVisibility(View.GONE);
            mSearchLayout.setVisibility(View.VISIBLE);
            mPullRecyclerView.setVisibility(View.VISIBLE);
        }

    }

    private void noData() {

        if (mNoDataLayout.getVisibility() != View.VISIBLE) {
            mNoDataLayout.setVisibility(View.VISIBLE);
            mConnectErrorLayout.setVisibility(View.GONE);
            mSearchLayout.setVisibility(View.GONE);
        }
    }

    private void connectNetError() {
        mNoDataLayout.setVisibility(View.GONE);
        mConnectErrorLayout.setVisibility(View.VISIBLE);
        mSearchLayout.setVisibility(View.GONE);
        mPullRecyclerView.setVisibility(View.GONE);
    }

    @NeedsPermission(Manifest.permission.CALL_PHONE)
    void needpermission() {
        if (!TextUtils.isEmpty(mTelNum)) {
            Uri uri = Uri.parse("tel:" + mTelNum);
            Intent intent = new Intent();
//                    intent.setAction(Intent.ACTION_DIAL); // 调用拨号盘
            intent.setAction(Intent.ACTION_CALL); // 调用拨号
            intent.setData(uri);
            startActivity(intent);

        }
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        BaseOrderListPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale(Manifest.permission.CALL_PHONE)
    void showRational(final PermissionRequest request) {
        new AlertDialog.Builder(mActivity)
                .setPositiveButton("允许", (dialog, which) ->
                        request.proceed())
                .setNegativeButton("拒绝", (dialog, which) ->
                        request.cancel())
                .setCancelable(false)
                .setMessage("请允许获取打电话权限")
                .show();
    }

    @OnPermissionDenied(Manifest.permission.CALL_PHONE)
    void Denied() {
        ToastUtils.showShortToast(mActivity, "权限不足,您没有开启此应用的使用打电话权限。请到系统设置-->权限管理 开启打电话使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下打电话权限！");
    }

    @OnNeverAskAgain(Manifest.permission.CALL_PHONE)
    void AskAgin() {
        ToastUtils.showShortToast(mActivity, "权限不足,您没有开启此应用的使用打电话权限。请到系统设置-->权限管理 开启打电话使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下打电话权限！");
    }

    @Override
    public boolean onBackPressedSupport() {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
            return true;
        }
        return super.onBackPressedSupport();
    }

    private void closeInputMethod(View view) {
        InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();
        if (isOpen) {
            // imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//没有显示则显示
            imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
